package uy.edu.fing.pgsegesb.authentication;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.picketlink.identity.federation.api.wstrust.WSTrustClient;
import org.picketlink.identity.federation.api.wstrust.WSTrustClient.SecurityInfo;
import org.picketlink.identity.federation.core.exceptions.ParsingException;
import org.picketlink.identity.federation.core.wstrust.WSTrustException;
import org.picketlink.identity.federation.core.wstrust.plugins.saml.SAMLUtil;
import org.w3c.dom.Element;

public class WSTrustHelper {

	
	public static boolean validateToken(String serviceName, String servicePort, String URI, String stsUser, String stsPass, Element assertion) throws Exception
	{
		  // crear una instancia WSTrustClient
	      WSTrustClient client = new WSTrustClient(serviceName, servicePort, URI, 
	            new SecurityInfo(stsUser, stsPass));
	      
	      // Imprimir la assertion 
	      System.out.println("SAMLV2.0 Assertion obtenida");
	      printAssertion(assertion);
	 
	      // validar la SAML assertion.
	      try
	      {
	         return client.validateToken(assertion);
	      }
	      catch (WSTrustException wse)
	      {
	         System.out.println("\n\nFailed to validate SAMLV2.0 Assertion: " + wse.getMessage());
	         wse.printStackTrace();
	      }
	      return false;
	}
	
	
	 
	   private static void printAssertion(Element assertion) throws Exception
	   {
	      TransformerFactory tranFactory = TransformerFactory.newInstance();
	      Transformer aTransformer = tranFactory.newTransformer();
	      Source src = new DOMSource(assertion);
	      Result dest = new StreamResult(System.out);
	      aTransformer.transform(src, dest);
	   }
}
